<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi as UserApi;
use Think\Model;

class MaterialController extends AdminController {
   public function index(){
      $this->display();
   }
   public function changeStatus($method=null,$table=null){
      if ( empty($_REQUEST['id']) ) {
         $this->error('请选择要操作的数据!');
      }
      $string = implode("-",$_REQUEST['id']);
      $table = strtolower($table);
      add_erp_log('Material',$table,$string,strtolower($method),strtolower($method)." id ".$string);
      switch ( strtolower($method) ){
         case 'forbid':
            $this->forbid($table);
            break;
         case 'resume':
            $this->resume($table);
            break;
         case 'delete':
            $this->delete($table,array(),array('success'=>'已拒绝该申请！', 'error'=>'错误的操作！'));
            break;
         default:
            $this->error($method.'参数非法');
      }
   }
   public function del($table=null,$id=null){
      $model = M($table);
      $res = $model->where(array('id'=>$id))->delete();
      if($res){
         $this->success("删除成功");
      }else{
         $this->error("删除失败");
      }
   }
   /***
    * 分类管理
    */
   public function classifymanage(){
      $model = M('Material_classify');
      $res = $model->order('classify_no asc')->select();
      $this->assign('_list',$res);
      $this->title = "货别管理";
      $this->display();
   }
   public function addclassify(){
      if(IS_POST){
         $model = M('Material_classify');
         $rules = array(
             array('classify','require','请输入货别！'),
             array('classify_no','require','请输入货别编号！'),
             array('classify_no', '/^[0-9]$/','货别编码为1位数字' , 1 , 'regex' ,1),
         );
         if(!$model->validate($rules)->create()){
            $this->error($model->getError());
         }else{
            $model->createAt = time();
            $model->updateAt = time();
            if($model->add()){
               add_erp_log('Material','material_classify',I('classify'),'add','新增分类:'.I('classify').'，分类编号:'.I('classify_no'));
               $this->success("新增成功！",U('classifymanage'));
            }else{
               $this->error("新增失败，类名或编号存在！");
            }
         }
      }else{
         $this->title = "新增货别";
         $this->display();
      }
   }
   /***
    * 水果分类管理
    * @author Scor&&zht
    */
   public function fruitclassifymanage(){
      $type=999;
      if(I('type')!==""){
         $type= I('type');
         $map['status'] = I('type');
      }
      $fruitclassify = I('fruit_classify');
      if($fruitclassify){
         $map['fruit_classify'] = array('like', '%' . (string) $fruitclassify . '%');
      }
      $Model = M('Material_fruitclassify');
      $res = $this->lists("Material_fruitclassify",$map);
      $this->type = $type;
      $this->assign('_list',$res);
      $this->display();
   }
   public function addfruitclassify(){
      if(IS_POST){
         $model = M('Material_fruitclassify');
         $rules = array(
             array('fruit_classify_no','require','请输入水果分类编号！'),
             array('fruit_classify','require','请输入输水果分类！'),
             array('fruit_classify_no', '/^[0-9][0-9]$/','分类编码为两位数字' , 1 , 'regex' ,1),
             array('per2_time', '/^[0-9]/','阶段日期不能为负数' , 1 , 'regex' ,1),
             array('per3_time', '/^[0-9]/','阶段日期不能为负数' , 1 , 'regex' ,1),
         );
         if(!$model->validate($rules)->create()){
            $this->error($model->getError());
         }else{
            $model->create();
            $model->createAt = time();
            $model->updateAt = time();
            if($model->add()){
               add_erp_log('Material','material_fruit_classify',I('fruit_classify'),'add','新增水果分类:'.I('fruit_classify').'，水果分类编号:'.I('fruit_classify_no'));
               $this->success("新增成功！",U('fruitclassifymanage'));
            }else{
               $this->error("新增失败，水果类名或编号存在！");
            }
         }
      }else{
         $classify_arr=M('Material_fruitclassify')->getField('fruit_classify_no',true);
         for($i=1;$i<99;$i++){
            if($i<10){
               $i='0'.$i;
            }
            if(!in_array($i,$classify_arr)){
               $this->fruit_classify_no=$i;
               break;
            }
         }
         $this->title = "新增水果分类";
         $this->display();
      }
   }
   public function editfruitclassify(){
      if(IS_POST){
         $model = M('Material_fruitclassify');
         $rules = array(
             array('fruit_classify_no','require','请输入水果分类编号！'),
             array('fruit_classify','require','请输入输水果分类！'),
             array('fruit_classify_no', '/^[0-9][0-9]$/','分类编码为两位数字' , 1 , 'regex' ,1),
             array('per2_time', '/^[0-9]/','阶段日期不能为负数' , 1 , 'regex' ,1),
             array('per3_time', '/^[0-9]/','阶段日期不能为负数' , 1 , 'regex' ,1),
         );
         if(!$model->validate($rules)->create()){
            $this->error($model->getError());
         }else{
            $model->create();
            $model->createAt = time();
            $model->updateAt = time();
            if($model->save()){
               add_erp_log('Material','material_fruit_classify',I('fruit_classify'),'update','修改水果分类:'.I('fruit_classify').'，水果分类编号:'.I('fruit_classify_no'));
               $this->success("修改成功！",U('fruitclassifymanage'));
            }else{
               $this->error("修改失败！");
            }
         }
      }else{
         $map['id'] = I('id');
         $res = M('material_fruitclassify')->where($map)->find();
         $this->classify = $res;
         $this->title = "修改水果分类";
         $this->display();
      }
   }
   /***
    * 商品名管理
    * @author Scor&&zht
    */
   public function pnamemanage(){
      $map['belong_to'] = I('belong_to');
      $model = M('Material_pname');
      $res = $model->where($map)->order('pname_no asc')->select();
      $this->assign('_list',$res);
      $this->belong_to = I('belong_to');
      $this->title = "商品名管理";
      $this->display();
   }
   public function addpname(){
      if(IS_POST){
         $model = M('Material_pname');
         $rules = array(
             array('pname_no','require','请输入水果编号！'),
             array('pname','require','请输入输水果！'),
             array('pname_no', '/^[0-9][0-9]$/','水果编码为两位数字' , 1 , 'regex' ,1),
         );
         if(!$model->validate($rules)->create()){
            $this->error($model->getError());
         }else{
            $model->create();
            $model->createAt = time();
            $model->updateAt = time();
            if($model->add()){
               add_erp_log('Material','material_pname',I('pname'),'add','新增水果名:'.I('pname').'，水果编号:'.I('pname_no'));
               $this->success("新增成功！",U(' mn    ',array('belong_to'=>I('belong_to'))));
            }else{
               $this->error("新增失败，商品名或编号存在！");
            }
         }
      }else{
         $map['belong_to']=I('belong_to');
         $pname_arr=M('Material_pname')->where($map)->getField('pname_no',true);
         for($i=1;$i<99;$i++){
            if($i<10){
               $i='0'.$i;
            }
            if(!in_array($i,$pname_arr)){
               $this->pname_no=$i;
               break;
            }
         }
         $this->belong_to = I('belong_to');
         $this->title = "新增商品名";
         $this->display();
      }
   }
   public function editpname(){
      $model = M('Material_pname');
      if(IS_POST){
         $model->create();
         $model->updateAt = time();
         if($model->save()){
            $this->success("修改成功",U('Material/fruitclassifymanage'));
         }else{
            $this->error("修改失败，商品名或编号存在");
         }
      }else{
         $map['id'] = I('id');
         $res = $model->where($map)->find();
         $this->info = $res;
         $this->title = "编辑商品名";
         $this->display();
      }
   }
   /***
    *商品管理
    */
   public function productmanage(){
      $map['status'] = array('in','0,1');
      $status = 999;
      if(I('classify')){
         $map['BIN'] = array("like","".I('classify')."%");
      }
      if(I('status')!==""){
         $status = I('status');
         $map['status'] = I('status');
      }
      if(I('BIN')){
         $map['BIN'] = array("like","%".I('BIN')."%");
      }
      if(I('pname')){
         $map['pname'] = array("like","%".I('pname')."%");
      }
      $res = $this->lists('Material_product',$map);
      $classify = M('Material_classify')->where(array('status'=>1))->select();
      $this->assign('_classify',$classify);
      $this->assign('_list',$res);
      $this->title = "商品管理";
      $this->status = $status;
      $this->display();
   }
   public function productdel($BIN=""){
      $map['BIN']=$BIN;
      M('Material_product')->where($map)->delete();
      M('Inventory_warn')->where($map)->delete();
      if(substr($BIN,0,1)=='2'){
         M('Material_product_fee')->where($map)->delete();
         M('Material_product_subpro')->where($map)->delete();
      }
      $this->success("删除成功");
   }
   public function editproduct(){
      $model = M('material_product');
      if(IS_POST){
         $BIN=I('BIN');
         $map['BIN']=$BIN;
         $data['spec']=I('spec');
         $res=$model->where($map)->save($data);

         if($res!==false){
            if(substr(I('BIN'),0,1)=='2'){
               $feeModel=M('Material_product_fee');
               $subproModel=M('Material_product_subpro');
               $feeData=array(
                   'trans_fee'=>I('express_fee'),
                   'process_fee'=>I('process_fee'),
                   'BIN'=>$BIN,
               );
               $extramap['BIN']=I('BIN');
               $feeModel->where($extramap)->delete();
               $feeModel->where($extramap)->add($feeData);
               $subproIdArr=I('subpro_id');
               $subproNumArr=I('num');
               $subproModel->where($extramap)->delete();
               for($i=0;$i<count($subproIdArr);$i++){
                  $subproData=array(
                      'subpro_id'=>$subproIdArr[$i],
                      'num'=>$subproNumArr[$i],
                      'BIN'=>$BIN,
                      'createAt'=>NOW_TIME
                  );
                  $subproModel->add($subproData);
               }
            }
            $this->success("修改成功");
         }else{
            $this->error("修改失败");
         }
      }else{
         $BIN = I('BIN');
         $this->BIN=$BIN;
         $this->display();
      }
   }
   public function addproduct(){
      if(IS_POST){
         $model = M('Material_product');
         $rules = array(
             array('classify','require','请选择货别！'),
             array('fruit_classify','require','请选择水果分类！'),
             array('pname','require','请选择商品名！'),
             array('spec','require','请填写规格！'),
             array('spec', '/[\d]+[\x{4e00}-\x{9fa5}]\/[\x{4e00}-\x{9fa5}]$/u','规格正确格式：20斤/箱' , 1 , 'regex' ,1),
             array('spec_no','require','请填写规格编码！'),
             array('spec_no', '/^[0-9][0-9]$/','规格编码为两位数字' , 1 , 'regex' ,1),
         );
         if(!$model->validate($rules)->create()){
            $this->error(M('Material_product')->getError());
         }else{
            $BIN=I('classify_no').I('fruit_classify_no').I('pname_no').I('spec_no');
            $model->BIN =$BIN;
            if($model->add()){
               $feeModel=M('Material_product_fee');
               $subproModel=M('Material_product_subpro');
               $feeData=array(
                  'trans_fee'=>I('express_fee'),
                  'process_fee'=>I('process_fee'),
                  'BIN'=>$BIN
               );
               $subproDataList=[];
               $subproIdArr=I('subproId');
               $subproNumArr=I('subproNum');
               for($i=0;$i<count($subproIdArr);$i++){
                  $subproDataList[]=array(
                     'BIN'=>$BIN,
                      'subpro_id'=>$subproIdArr[$i],
                      'num'=>$subproNumArr[$i]
                  );
               }
               $feeModel->add($feeData);
               $subproModel->addAll($subproDataList);
               add_erp_log('Material','material_product',I('pname'),'add','新增商品:'.I('pname').'，BIN:'.$model->BIN);
               $this->success("商品添加成功",U('material/productmanage'));
            }else{
               $this->error("商品已经存在");
            }
         }
      }else{
         $spec=I('spec');
         $this->spec=$spec;
         $this->title = "新增商品";
         $this->display();
      }
   }
   public function productreview(){
      $map['status'] = 9;
      $res = $this->lists('Material_product',$map);
      $this->assign('_list',$res);
      $this->title = "商品审核";
      $this->display();
   }
   public function productforbid($BIN=""){
      $inventoryModel=M('Inventory_warn');
      $materialModel=M('Material_product');
      $map['BIN']=$BIN;
      $data['status']=0;
      $res1=$inventoryModel->where($map)->save($data);
      $res2=$materialModel->where($map)->save($data);
      if($res1&&$res2){
         $this->success("禁用成功");
      }else{
         $this->error("禁用失败");
      }
   }
   public function productresume($BIN=""){
      $inventoryModel=M('Inventory_warn');
      $materialModel=M('Material_product');
      $map['BIN']=$BIN;
      $data['status']=1;
      $res1=$inventoryModel->where($map)->save($data);
      $res2=$materialModel->where($map)->save($data);
      if($res1&&$res2){
         $this->success("启用成功");
      }else{
         $this->error("启用失败");
      }
   }
   public function proExport() {
      $where = "";
      if(I('classify')){
         $where = "and BIN like '%".I('classify')."%' ";
      }
      if(I('status')!==""){
         $where = "and status = ".I('status')." ";
      }
      if(I('BIN')){
         $where = "and BIN like '%".I('BIN')."%' ";
      }
      if(I('pname')){
         $where = "and BIN like '%".I('pname')."%' ";
      }

      $sql = "select BIN,classify,fruit_classify,pname,spec from gr_material_product  where 1=1 ".$where."";
      $Model = new Model();
      $data = $Model->query($sql);
//      dump($data);
//      return false;
      if ($data){
         add_erp_log('Material','material_product','商品表','export','导出商品表');

//         $i = 0;
//         foreach($data as $key => $val){
//            $data[$i]['spec'] = get_name_by_id($val['BIN'],'Material_product','BIN','spec');
//            $data[$i]['classify'] = get_name_by_id($val['BIN'],'Material_product','BIN','classify');
//            $i++;
//         }
         //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
         import("Org.Util.PHPExcel");
         import("Org.Util.PHPExcel.Writer.Excel5");
         import("Org.Util.PHPExcel.IOFactory.php");

         $filename = "output_order_excel";

         $headArr = array("BIN","货别", "水果分类","商品","规格");
         $title = "实时库存列表";
         $this->getExcel($filename, $headArr, $data, $title);
      }else{
         $this->error("没有可导出的数据！");
      }
   }
   private function getExcel($fileName, $headArr, $data, $title) {
      //对数据进行检验
      if (empty($data) || !is_array($data)) {
         //die("data must be a array");
      }
      //检查文件名
      if (empty($fileName)) {
         exit;
      }
      // H:i:s
      $date = date("Y_m_d_H_i_s", time());
      //$date = date("Y_m_d",time());
      $fileName .= "_{$date}.xls";

      //创建PHPExcel对象，注意，不能少了\
      $objPHPExcel = new \PHPExcel();
      $objProps = $objPHPExcel->getProperties();

      //第一列设置报表时间范围
      $key = ord("A");
      $colum = chr($key);
      $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);


      //第二列设置报表列头
      $key = ord("A");
      foreach ($headArr as $v) {
         $colum = chr($key);
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
         $key += 1;
      }

      $column = 3;
      $objActSheet = $objPHPExcel->getActiveSheet();
      foreach ($data as $key => $rows) { //行写入
         $span = ord("A");
         foreach ($rows as $keyName => $value) {// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j . $column, $value);
            $objActSheet->getColumnDimension('a')->setWidth(15);
            $objActSheet->getColumnDimension('b')->setWidth(10);
            $objActSheet->getColumnDimension('c')->setWidth(15);
            $objActSheet->getColumnDimension('d')->setWidth(20);
            $objActSheet->getColumnDimension('e')->setWidth(20);
            if (count($headArr) == 12){
               $objActSheet->getColumnDimension('h')->setWidth(20);
               $objActSheet->getColumnDimension('i')->setWidth(20);
               $objActSheet->getColumnDimension('j')->setWidth(30);
               $objActSheet->getColumnDimension('l')->setWidth(100);
            }else{
               $objActSheet->getColumnDimension('g')->setWidth(20);
               $objActSheet->getColumnDimension('h')->setWidth(20);
               $objActSheet->getColumnDimension('i')->setWidth(30);
               $objActSheet->getColumnDimension('j')->setWidth(30);
               $objActSheet->getColumnDimension('k')->setWidth(100);
            }
            $span++;
         }
         $column++;
      }

      $fileName = iconv("utf-8", "gb2312", $fileName);
      //重命名表
      // $objPHPExcel->getActiveSheet()->setTitle('test');
      //设置活动单指数到第一个表,所以Excel打开这是第一个表
      $objPHPExcel->setActiveSheetIndex(0);
      header('Content-Type: application/vnd.ms-excel');
      header("Content-Disposition: attachment;filename=\"$fileName\"");
      header('Cache-Control: max-age=0');

      $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
      $objWriter->save('php://output'); //文件通过浏览器下载
      exit;
   }
   public function bincheck(){
      $res = M('Material_product')->select();
      foreach($res as $k=>$v){
         $fruit_classify_no = get_no_by_tag($v['BIN'],'fruit_classify_no');
         $pname_no = get_no_by_tag($v['BIN'],'pname_no');
         $map['pname_no'] = $pname_no;
         $map['belong_to'] = $fruit_classify_no;
         $p = M('Material_pname')->where($map)->find();
         if($p['pname']==$v['pname']){}else{
            dump($p['pname']);
            dump($v);
         }
      }
   }
   /**
    * ajax获取商品货别
    */
   public function ajaxGetClassify(){
      $model=M('Material_classify');
      $res=$model->where(array('status'=>1))->select();
      $this->ajaxReturn($res);
   }
   /**
    * ajax自动获取规格编码
    * @param $BIN
    */
   public function ajaxAutoGetSpecNo($BIN){
      $model=M('Material_product');
      $map['BIN']=array('like',$BIN.'%');
      $BINArr=$model->where($map)->order('BIN asc')->getField('BIN',true);
      if(substr($BINArr[0],5,2)!='01'&&substr($BINArr[0],5,2)!='00'){
            $this->ajaxReturn('01');
      }
      for($i=0;$i<100;$i++){
         if($BINArr[$i+1]!=$BINArr[$i]+1){
            $specNo=substr($BINArr[$i]+1,5,2);
            break;
         }
      }
      $this->ajaxReturn($specNo);
   }
   /**
    * ajax获取水果名关联水果分类
    */
   public function ajaxGetFruitNameWithFruitClassify(){
      $sql="select a.pname_no,a.pname,b.fruit_classify_no,b.fruit_classify
            from gr_material_pname a,gr_material_fruitclassify b where
            a.belong_to=b.fruit_classify_no and a.status=1 and b.status=1";
      $model=new Model();
      $res=$model->query($sql);
      $this->ajaxReturn($res);
   }
   /**
    * ajax获取正价对应原包装规格
    * @param string $BIN
    */
   public function ajaxGetYbzSpec($BIN=""){
      $map['BIN']=array('like',"".$BIN."%");
      $specArr=M('Material_product')->where($map)->getField('spec',true);
      $this->ajaxReturn($specArr);
   }
   public function ajaxGetEditProduct($BIN){
      $model=new Model();

      if(substr($BIN,0,1)=='2'){
         $sql="select a.*,ifnull(b.trans_fee,0) as trans_fee,ifnull(b.process_fee,0) as process_fee from gr_material_product a LEFT JOIN gr_material_product_fee b on a.BIN=b.BIN where a.BIN='".$BIN."'";
      }else{
         $sql="select a.* from gr_material_product a where a.BIN='".$BIN."'";
      }
      $res=$model->query($sql);
      $this->ajaxReturn($res[0]);
   }
   public function ajaxGetProductSubpro($BIN){
      $model=new Model();
      $sql="select a.*,b.pname,b.spec,c.unitprice from gr_material_product_subpro a,gr_subpro_product b,gr_subpro_productstock c where a.BIN=$BIN and c.BIN=a.subpro_id and a.subpro_id=b.id and c.dpid=999";
      $res=$model->query($sql);
      $this->ajaxReturn($res);
   }
}
